<template>
  <div class="employees-detail-container">
    <div class="app-container">
      <el-card>
        <!-- 放置表单 -->
        <el-form
          ref="userForm"
          label-width="120px"
          style="margin-left: 120px; margin-top: 30px"
          :model="userObj"
          :rules="rules"
        >
          <el-form-item label="姓名:" prop="username">
            <el-input v-model="userObj.username" style="width: 300px" />
          </el-form-item>
          <el-form-item label="手机">
            <el-input v-model="userObj.mobile" style="width: 300px" disabled />
          </el-form-item>
          <el-form-item label="入职时间" prop="timeOfEntry">
            <el-date-picker
              v-model="userObj.timeOfEntry"
              type="date"
              class="inputW"
            />
          </el-form-item>
          <el-form-item label="员工头像">
            <ImageUpload ref="imgupload" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editEmploy">更新</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getUserPhoto } from '@/api/user'
import { editEmployeesApi } from '@/api/employees'
import { Message } from 'element-ui'
export default {
  name: 'EmployeesDetail',
  data() {
    return {
      userObj: {},
      id: this.$route.query.id,
      rules: {
        username: [
          { required: true, message: '员工姓名不能为空', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '员工入职日期不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // id() {
    //   return this.$route.query.id
    // }
  },
  created() {
    this.getUserObj()
  },
  methods: {
    editEmploy() {
      // 1.兜底效验
      this.$refs.userForm.validate(async key => {
        if (!key) return
        // 判断是否图片全部上传完成
        if (!this.$refs.imgupload.isUpload) {
          Message.warning('还有图片未上传完成，请稍等')
          return
        }
        // 2.1获取图片信息
        // 判断是否有图片提交
        if (this.$refs.imgupload.fileList[0]?.url) {
          this.userObj.staffPhoto = this.$refs.imgupload.fileList[0].url
        } else {
          Message.warning('头像不能为空')
          return
        }
        // 2.调用接口
        await editEmployeesApi(this.userObj)
        // 3.提示修改成功
        Message.success('修改成功')
        // 4.可选 回到上一页
        this.$router.go(-1)
      })
    },
    /**
     * 获取回填信息
     */
    async getUserObj() {
      const { data } = await getUserPhoto(this.id)
      this.userObj = data
      console.log(data)
      // 回填头像
      this.$refs.imgupload.fileList = [
        { url: data.staffPhoto }
      ]
    }
  }
}
</script>
